package com.chenxiao.mybatisplus.mq;

import com.chenxiao.mybatisplus.entity.Order;
import com.chenxiao.mybatisplus.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.springframework.messaging.Message;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @Author: CX
 * @Date: Created in  2023/03/11 16:22
 * @version: v1.0
 * @Description: TODO
 *  订单消费类，异常发送订单消息
 **/
@Component
@Slf4j
public class RabbitmqConsumer {


    @Resource
    JavaMailSender javaMailSender;
    @Resource
    MailProperties mailProperties;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    TemplateEngine templateEngine;
    @Resource
    private OrderService orderService;


    @RabbitListener(queues = "OrderDirectQueue")//监听的队列名称 TestDirectQueue
    @RabbitHandler
    public void process(Map employee, Message message, Channel channel) throws IOException {

          //System.out.println("DirectReceiver消费者2收到消息  : " + message.toString());


        // Map<String, Object> employee = (Map) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = headers.get("id") +"";

        if (redisTemplate.hasKey("mail_log_"+ msgId)) {
            //redis 中包含该 key，说明该消息已经被消费过
            log.info(msgId + ":消息已经被消费");
            channel.basicAck(tag, false);//确认消息已消费
            return;
        }
        //收到消息，发送邮件
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            helper.setTo("932900547@qq.com");
            helper.setFrom(mailProperties.getUsername());
            helper.setSubject("入职欢迎");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name", employee.get("name"));
            context.setVariable("posName", employee.get("posName"));
            context.setVariable("joblevelName", employee.get("joblevelName"));
            context.setVariable("departmentName", employee.get("departmentName"));

            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            javaMailSender.send(msg);
            redisTemplate.opsForSet().add("mail_log_"+ msgId,msgId);
            channel.basicAck(tag, false);
            log.info(msgId + ":邮件发送成功");
        } catch (MessagingException e) {
            channel.basicNack(tag, false, true);
            e.printStackTrace();
            log.error("邮件发送失败：" + e.getMessage());
        }
    }
    @RabbitListener(queues = "OrderQueue")//监听的队列名称 TestDirectQueue
    public void processOrder(Object object, Message message, Channel channel) throws IOException {
        MessageHeaders headers = message.getHeaders();
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

        String msgId = headers.get("id") +"";
        if (redisTemplate.hasKey("order_log_"+ msgId)) {
            //redis 中包含该 key，说明该消息已经被消费过
            log.info(msgId + ":消息已经被消费");
            channel.basicAck(tag, false);//确认消息已消费
            return;
        }
        try {
            Object payload = message.getPayload();
            if(payload != null && payload instanceof  Order){
                Order order = (Order) payload;
               // orderService.insertOrder(order);
            }
            redisTemplate.opsForSet().add("order_log_" + msgId, msgId);
            channel.basicAck(tag, false);
            log.info(msgId + ":订单发送成功");
        }catch (Exception e){
            channel.basicNack(tag, false, true);
            e.printStackTrace();
            log.error("邮件发送失败：" + e.getMessage());
        }

    }

}
